package rad.framework.mda.jpagen.actions;

import rad.framework.mda.generator.Console;
import rad.framework.mda.util.ModelUtil;

import org.eclipse.emf.common.util.EList;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.uml2.uml.Class;
import org.eclipse.uml2.uml.Element;
import org.eclipse.uml2.uml.Enumeration;
import org.eclipse.uml2.uml.NamedElement;
import org.eclipse.uml2.uml.Property;
import org.eclipse.uml2.uml.Stereotype;

/**
 * @author boudyacho
 * 
 */
public class AddEnumerationActionExtension extends
		BaseUtiltiyActionExtension {

	protected static final String ENUM = "javax.persistence.Enumerated";

	protected static final String ENUM_TYPE = "javax.persistence.EnumType";

	public void fillContextMenu(IMenuManager aMenu) {
		getSubMenu(aMenu).add(new AddEnumerationAction());
	}

	protected void execute(Class clazz) {
		EList<NamedElement> list = clazz.getMembers();
		for (NamedElement namedElement : list) {
			if (namedElement instanceof Property) {
				execute((Property) namedElement);
			}
		}
	}

	protected void execute(Property property) {
		if (property.getType() instanceof Enumeration
				&& !ModelUtil.isStereotypeApplied(property, ENUM)) {
			setEnumAsString(property);
			Console.getStream().println(
					"Set Enum Type as String - " + property.getQualifiedName());
		}
	}

	protected void setEnumAsString(Element element) {
		Stereotype stereotype = (Stereotype) ModelUtil.getProfileElement(
				element, ENUM);
		Element e = ModelUtil.getProfileElement(element, ENUM_TYPE);
		if (stereotype != null && e != null) {
			if (e instanceof Enumeration) {
				element.applyStereotype(stereotype);
				element.setValue(stereotype, "value", ((Enumeration) e)
						.getOwnedLiteral("STRING"));
			}
		}
	}

	private class AddEnumerationAction extends BaseUtilityAction {
		private static final String LABEL = "Add Enumeration Stereotypes";

		public AddEnumerationAction() {
			super(LABEL);
		}
	}
}
